package cn.hist.hfp.controller;

import cn.hist.hfp.RoleType;
import cn.hist.hfp.entity.Pet;
import cn.hist.hfp.service.PetService;
import cn.hist.hfp.util.Authentication;
import cn.hist.hfp.util.MyResponse;
import cn.hist.hfp.vo.PetVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/pet")
public class PetController {

    private final
    PetService petService;

    private final
    Authentication authentication;

    private final
    MyResponse<PetVO> myResponse;

    @Autowired
    public PetController(PetService petService, Authentication authentication, MyResponse<PetVO> myResponse) {
        this.petService = petService;
        this.authentication = authentication;
        this.myResponse = myResponse;
    }

    @PostMapping
    public ResponseEntity<PetVO> create(@RequestBody Pet pet, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return myResponse.response(201, authentication.refreshToken(token), petService.create(pet));
    }

    @GetMapping("/{id}")
    public PetVO findOne(@PathVariable int id) {
        return petService.findOne(id);
    }

    @GetMapping("/page/{page}")
    public ResponseEntity<List<PetVO>> findSome(@PathVariable int page, @RequestParam String species) {
        MyResponse<List<PetVO>> myResponse = new MyResponse<>();
        return myResponse.response(200, petService.findSome(page, species));
    }

    @GetMapping("/page")
    public int numberOfPages(@RequestParam String species) {
        return petService.numberOfPages(species);
    }

    @PutMapping
    public PetVO update(@RequestBody Pet pet) {
        return petService.update(pet);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Integer> delete(@PathVariable int id, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        MyResponse<Integer> myResponse = new MyResponse<>();
        return myResponse.response(200, authentication.refreshToken(token), petService.delete(id));
    }
}